﻿using Pay.Core;
using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.IO;
using Pay.DTO;

namespace Pay.Web {
	/// <summary>
	/// 通用MVC的Controller，JSON的重写实现EF的JSON时对象循环的BUG
	/// </summary>
	public class GeneralController : Controller {
		protected userCookie currentUser;
        /// <summary>
        /// 验证返回的错误提示
        /// </summary>
        public string ModelError {
            get {
                StringBuilder sb = new StringBuilder();
                foreach (var item in ModelState.Values) {
                    foreach (var er in item.Errors) {
                        if (!string.IsNullOrEmpty(er.ErrorMessage))
                            sb.Append(er.ErrorMessage + ",");
                        else
                            sb.Append(er.Exception.Message + ",");
                    }
                }
                return sb.ToString().TrimEnd(',');
            }
        }
        public GeneralController() {
		}

		protected override JsonResult Json(object data, string contentType, Encoding contentEncoding, JsonRequestBehavior behavior) {
			return new JsonNetResult(data, behavior, contentType, contentEncoding);
		}

		protected override void OnActionExecuting(ActionExecutingContext filterContext) {
			var cookie = Request.Cookies[FormsAuthentication.FormsCookieName];
			if (cookie != null) {
				var ticket = FormsAuthentication.Decrypt(cookie.Value);
				currentUser = ticket.UserData.ToObject<userCookie>();
			}
			base.OnActionExecuting(filterContext);
		}

		/// <summary>
		/// 创建用户Cookie
		/// </summary>
		/// <param name="name"></param>
		/// <param name="userData"></param>
		/// <param name="remember3day"></param>
		protected void FormsCookieSave(string name, userCookie userData, bool remember3day) {
			DateTime issueDate = DateTime.Now;
			DateTime expiration = issueDate.Add(FormsAuthentication.Timeout);
			if (remember3day)
				expiration = issueDate.AddDays(3);
			FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, name, issueDate, expiration, false, userData.ToJson());
			string hashTicket = FormsAuthentication.Encrypt(ticket);
			HttpCookie userCookie = new HttpCookie(FormsAuthentication.FormsCookieName, hashTicket);
			if (remember3day)
				userCookie.Expires = expiration;
			Response.Cookies.Add(userCookie);
		}

        protected List<string> UploadList(string action_dir, string fileInput = "file", bool use_time = false) {
            List<string> paths = new List<string>();
            if (Request.Files.Count == 0)
                return null;
            if (Request.Files.Count > 0) {
                for (int i = 0; i < Request.Files.Count; i++) {
                    var file = Request.Files[i];
                    if (file == null)
                        return null;
                    var time = DateTime.Now.Date;

                    var dir = string.Format("{0}", action_dir).TrimEnd('/');
                    if (use_time) dir += "/" + (time.Ticks).ToString().TrimEnd('0');

                    string ext = Path.GetExtension(file.FileName);

                    byte[] file_byte = new byte[file.ContentLength];
                    file.InputStream.Read(file_byte, 0, file.ContentLength);

                    var fileType = FileValid.GetFileType(file_byte);
                    if (fileType != FileExtension.GIF && fileType != FileExtension.JPG && fileType != FileExtension.PNG)
                        throw new ServerErrorException("上传文件格式不正确");
                    MemoryStream mss = new MemoryStream(file_byte);
                    var oid = Guid.NewGuid().ToString("N");
                    var path = string.Format("{0}/{1}{2}", dir, oid, ext);
                    var oss = new AliyunOSS(DtoHelper._accessKeyId, DtoHelper._accessKeySecret, "");
#if DEBUG
                    var ok = oss.PutObject(DtoHelper.oss_bucketName, path, mss);
#else
                    var ok = oss.PutObject("glb-bucket", path, mss);
#endif
                    paths.Add(path);
                }
            }
            //释放内存
            GC.Collect();
            return paths;
        }


        protected string Upload(string action_dir, string fileInput = "file", bool use_time = false) {
			if (Request.Files.Count == 0)
				return null;

			var file = Request.Files[fileInput];
			if (file == null)
				return null;
			var time = DateTime.Now.Date;

			var dir = string.Format("{0}", action_dir).TrimEnd('/');
			if (use_time) dir += "/" + (time.Ticks).ToString().TrimEnd('0');

			string ext = Path.GetExtension(file.FileName);

			byte[] file_byte = new byte[file.ContentLength];
			file.InputStream.Read(file_byte, 0, file.ContentLength);

			var fileType = FileValid.GetFileType(file_byte);
			if (fileType != FileExtension.GIF && fileType != FileExtension.JPG && fileType != FileExtension.PNG)
				throw new ServerErrorException("上传文件格式不正确");
			MemoryStream mss = new MemoryStream(file_byte);
			var oid = Guid.NewGuid().ToString("N");
			var path = string.Format("{0}/{1}{2}", dir, oid, ext);
			var oss = new AliyunOSS(DtoHelper._accessKeyId, DtoHelper._accessKeySecret, "");
			var ok = oss.PutObject(DtoHelper.oss_bucketName, path, mss);
			//释放内存
			GC.Collect();
			return path;
		}
	}
	public class userCookie {
		public userCookie() { roles = new List<string>(); }
		public long user_id { get; set; }
		public List<string> roles { get; set; }
		/// <summary>
		/// 管理员的角色，如果是空就是超级权限，如果非空就按值查询
		/// </summary>
		public long? role_id { get; set; }
	}
}
